#include "MultiGateSolutionByDistance.h"
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <stdio.h>
#include <string>
#include <thread>
#include <vector>

#pragma comment(lib, "MultiGateSolutionByDistance.lib")

// 全局变量，用于记录用户是否在开门区域内
std::map<std::string, bool> usersInOpeningArea;
std::mutex mtx; // 用于同步对usersInOpeningArea的访问

// 模拟距离数据获取和闸机控制的主函数
static void monitorAndControlGate()
{
	std::vector<UserInfo_t> userInfo;
	if (initialize() != 0)
	{
		std::cerr << "Initialization failed!" << std::endl;
		return;
	}

	while (true)
	{
		if (getMasterInstance(userInfo) == 0)
		{
			std::lock_guard<std::mutex> lock(mtx);
			// 清除之前的数据
			usersInOpeningArea.clear();

			// 检查是否有用户在开门区域内
			for (const auto& user:userInfo)
			{
				if (user.distance >= 30 && user.distance <= 50)
				{
					// 检查是否已经有用户正在开门
					if (usersInOpeningArea.empty())
					{
						usersInOpeningArea[user.userId] = true;
						std::cout << "User " << user.userId << " is in the opening area, opening gate..." << std::endl;
						openGate(user.userId);

						// 假设闸门打开后用户需要2秒通过
						std::this_thread::sleep_for(std::chrono::seconds(2));

						// 用户通过闸门后，调用生成计费凭证
						genPurchaseVoucher(user.userId);
						std::cout << "Gate closed, voucher generated for user " << user.userId << std::endl;
					}
					else
					{
						std::cout << "User " << user.userId << " is in the opening area, but another user is opening the gate, please wait..." << std::endl;
					}
				}
				else
				{
					// 用户不在开门区域内，但是之前在开门区域内的用户已经通过了，清除记录
					if (usersInOpeningArea.find(user.userId) != usersInOpeningArea.end())
					{
						usersInOpeningArea.erase(user.userId);
					}
				}
			}

			// 清除开门区域记录（这里可以根据实际情况调整，例如用户通过闸机后延迟清除）
			usersInOpeningArea.clear();
		}

		std::this_thread::sleep_for(std::chrono::milliseconds(250)); // 每隔250ms检测一次
	}
}

int main()
{
	monitorAndControlGate();
	return 0;
}
